package business;

import entity.Event;
import entity.SearchResult;
import entity.User;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class UserManager {
    
    @PersistenceContext
    private EntityManager entityManager;
    
    @Inject
    private Principal principalUser;
    
    public void create(User user) {
        entityManager.persist(user);
    }
    
    public void save(User user) {
        entityManager.merge(user);
    }
    
    public boolean exist(String username) {
        return entityManager.find(User.class, username) != null;
    }
    
    public User getLoggedUser() {
        return entityManager.find(User.class, principalUser.getName());
    }
    
    public User find(String username) {
        return entityManager.find(User.class, username);
    }
    
    public List<Event> getCreatedEventsFromDate(User user, Date startingDate) {
        List<Event> matchingEventList = new ArrayList<>();
        if (user != null) {
            user = refresh(user);
            List<Event> eventList = user.getCreatedEvents();
            for (Event event : eventList) {
                if (startingDate.before(event.getDate())) {
                    matchingEventList.add(event);
                }
            }
        }
        return matchingEventList;
    }
    
    public List<SearchResult> search(String keyword) {
        Query query = entityManager.createNamedQuery("User.findByAttribute");
        query.setParameter("keyword", "%" + keyword + "%");
        List<Object[]> result = query.getResultList();
        List<SearchResult> searchResults = new ArrayList<>();
        for (Object[] attributes : result) {
            searchResults.add(new SearchResult((String)attributes[0], (String)attributes[1], (String)attributes[2]));
        }
        return searchResults;
    }

    public User[] findAll(List<String> usernames) {
        List<User> users = new ArrayList<>();
        for (String username : usernames) {
            User foundUser = entityManager.find(User.class, username);
            if (foundUser != null) {
                users.add(foundUser);
            }
        }
        return users.toArray(new User[users.size()]);
    }
    
    public User refresh(User user) {
        User newUser = entityManager.find(User.class, user.getUsername());
        entityManager.refresh(newUser);
        return newUser;
    }

    public void delete(User currentUser) {
        entityManager.remove(entityManager.find(User.class, currentUser.getUsername()));
    }
}
